import requests, json, time, os
from log import logger

class Es():
    def __init__(self, server, port):
        self.server = server
        self.port = port


    def esUpload(self, vender, product, name, person, description, file):
        if vender == '' or product == '' or name == '' or person == '' or description == '':
            return False
        
        info = {
            "vender": vender,
            "product": product,
            "name": name,
            "person": person,
            "desc": description,
            "date": time.strftime("%Y-%m-%d", time.localtime())
        }
        logger.info(info)
        if os.path.isfile(file) is False:
            fileList = {
                        "file": ("name", file.encode("utf8")), 
                        "info": ("info", json.dumps(info))
                        }    
        else:
            fileList = {
                "file": ("name", open(file,"rb")), 
                "info": ("info", json.dumps(info))
                }    
        logger.info(fileList)

        # header = {
        #     "Content-Type": "multipart/form-data"
        # }
        
        try:
            es = requests.request(  method="put",
                                    url="http://%s:%s/log/upload/%s" % (self.server, self.port, vender),
                                    files=fileList)
        except:
            return {"errno": -1, "errinfo": "upload failed"}

        return json.loads(es.content.decode("utf8"))
    
# test
if __name__ == '__main__':
    esUpload(vender="snbc", 
            product="servo-driver", 
            name="test", 
            person="yanghaolin", 
            description="never", 
            filePath="C:\\Users\\bloath\\Desktop\\logUpload\\log\\1111")